package com.apexedu.portal.controller;

import com.apexedu.framework.dao.BaseDao;
import com.apexedu.framework.util.DBUtil;
import com.apexedu.framework.util.SysPropertiesUtil;
import com.apexedu.identity.IdConstants;
import com.apexedu.identity.entity.TSysUser;
import com.apexedu.identity.util.PolymorphismMD5;
import com.apexedu.portal.constant.ActionConstant;
import com.apexedu.portal.util.LittleTimer;
import com.apexedu.windowsad.ADOperator;
import com.apexedu.windowsad.ADUserInfo;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;

/**
 * 修改自己的密码、管理员重置用户密码
 */
@Controller
public class PwdController extends BaseController {

    @Resource
    private BaseDao baseDao;

    /**
     * 初始界面
     *
     * @return 初始界面
     */
    @RequestMapping(value = ActionConstant.Pwd.RequestMapping_init, method = RequestMethod.GET)
    public String init() {
        return ActionConstant.Pwd.Forward_init;
    }

    /**
     * 管理员重置用户的密码
     */
    @RequestMapping(value = "/uc/pwd/admin/{dealUserId}/{userPwdNew}", method = RequestMethod.POST)
    @ResponseBody
    public String resetPwdByAdmin(@PathVariable("dealUserId") String dealUserId,
                                  @PathVariable(ActionConstant.Pwd.Variable_userPwdNew) String userPwdNew,
                                  HttpServletRequest request, HttpServletResponse response) {
        debug("<<{}>> resetPwdByAdmin start", this.getClass().getSimpleName());
        LittleTimer timer = new LittleTimer();
        TSysUser loginUser = (TSysUser) request.getSession().getAttribute(IdConstants.SESSION_USER);
        try {
            if (loginUser != null && loginUser.getUserloginid().equals("admin")) { // 只有admin有权限修改别人密码
                String changeUserLoginId = DBUtil.queryField("select userloginid from t_sys_user where userid=?", dealUserId);
                String changeUserType = DBUtil.queryField("select case t.usertype when '1' then '教师' when '2' then '学生' else '其他' END from t_sys_user where userid=?", dealUserId);
                // 1. 修改数据库中的密码
                String sql = "update t_sys_user u set u.userpwd = ? where u.userloginid = ?";
                DBUtil.executeSQL(sql, PolymorphismMD5.hash(userPwdNew).toUpperCase(), changeUserLoginId);

                sql = "update TUSER u set u.password = ? where u.userid = ?";
                DBUtil.executeSQL(sql, PolymorphismMD5.hash(userPwdNew).toUpperCase(), changeUserLoginId);

                // 2. 修改ldap中用户的密码【上海工业学校需求】
                if ("true".equals(SysPropertiesUtil.get(IdConstants.HAS_LDAP))) {
                    String res = rePwdInLdapAD(changeUserLoginId,changeUserType, userPwdNew);
                    info("重置 LDAP 中用户 " + changeUserLoginId + " 的密码"+res);
                }
                return "成功重置用户 " + changeUserLoginId + " 的密码";
            } else {
                return ("未授权操作");
            }
        } catch (Exception e) {
            error("<<{}>> save error : {}", this.getClass().getSimpleName(), e);
            throw new RuntimeException(e);
        } finally {
            debug("<<{}>> save end : {}", this.getClass().getSimpleName(), timer.end());
        }
    }

    /**
     * 修改 LDAP 和 AD域中的用户密码【上海工业学校需求】
     * @param userloginid 要修改的用户账户
     * @param newPwd 新密码
     * @throws Exception
     */
    public static String rePwdInLdapAD(String userloginid,String serType, String newPwd) throws Exception {

//        String cn = LdapUtil.queryLudap(userloginid);
//        boolean succ = false;
//        String ouname = StringUtil.EMPTY;
//        for (String str : cn.split(",")) {
//            if (str.indexOf("ou=") == 0) {
//                ouname = str.substring(3);
//                succ = true;
//                break;
//            }
//        }
        boolean succ=true;
        if (succ) {//上海工业学校，启用了 apacheDS 和 windows AD域两个 ldap存储用户
//                    LdapUtil.updatePwdLdap(user.getUserloginid(), userPwdNew);
//            LdapUtil.deleteEntry(userloginid);
//            TSysUser newUser = new TSysUser();
//            newUser.setUsername(userloginid);
//            newUser.setUserloginid(userloginid);//uid=yingchenghua,ou=学生工作部xsc,o=上海市工业技术学校,dc=example,dc=com
//            newUser.setUserpwd(newPwd);
//            newUser.setOrname(ouname);
//            LdapUtil.addUser(newUser);

            // 3. 修改 Windows AD域中用户的密码【上海工业学校需求】
            ADUserInfo info = new ADUserInfo();
            info.setSamAccountName(userloginid);
            info.setPassword(newPwd);
            info.setOu(serType);
            ADOperator op = new ADOperator();
            op.changePassword(info);
            op.closeDirContext();
            return "true";
        }
        return "false";
    }


    /**
     * 个人修改自己的密码
     */
    @RequestMapping(value = ActionConstant.Pwd.RequestMapping_repwd, method = RequestMethod.GET)
    public void repwd(@PathVariable(ActionConstant.Pwd.Variable_userPwdOld) String userPwdOld,
                      @PathVariable(ActionConstant.Pwd.Variable_userPwdNew) String userPwdNew,
                      @PathVariable(ActionConstant.Pwd.Variable_dlmmnew) String dlmmnew,
                      HttpServletRequest request, HttpServletResponse response) {
        debug("<<{}>> repwd start", this.getClass().getSimpleName());
        LittleTimer timer = new LittleTimer();
        String userType="";
        TSysUser user = (TSysUser) request.getSession().getAttribute(IdConstants.SESSION_USER);
        PrintWriter out = null;
        try {
            out = response.getWriter();
            if (user != null) {
            	if ("1".equals(user.getUsertype())){
                    userType="教师";
                }else if ("2".equals(user.getUsertype())){
                    userType="学生";
                }else{
                    userType="其他";
                }
                if (user.getUserpwd().toUpperCase().equals(PolymorphismMD5.hash(userPwdOld).toUpperCase())) {
                    if (userPwdNew.equals(dlmmnew)) {
                        String hql = "update TSysUser u set u.userpwd = ? where u.userloginid = ?";
                        baseDao.executeHql(hql, PolymorphismMD5.hash(userPwdNew).toUpperCase(), user.getUserloginid());

                        String sql = "update TUSER u set u.password = ? where u.userid = ?";
                        DBUtil.executeSQL(sql, PolymorphismMD5.hash(userPwdNew).toUpperCase(), user.getUserloginid());

                        //修改ldap中用户的密码
                        if ("true".equals(SysPropertiesUtil.get(IdConstants.HAS_LDAP))) {
                            rePwdInLdapAD(user.getUserloginid(),userType,userPwdNew);
                        }
                        out.println("修改成功");
                    } else {
                        out.println("输入两次密码不一致");
                    }
                } else {
                    out.println("原密码不正确");
                }
            } else {
                out.println("未登录系统");
            }
        } catch (Exception e) {
            error("<<{}>> save error : {}", this.getClass().getSimpleName(), e);
            throw new RuntimeException(e);
        } finally {
            if(out!=null)
                out.close();
            debug("<<{}>> save end : {}", this.getClass().getSimpleName(), timer.end());
        }
    }
}
